import util from './util.js';
import {HEADER, TOKENNAME, TOKEN} from './../config.js';

/**
 * 发送请求
 */
export default function request(api, method, data, {noAuth = false, noVerify = false}) {
  const Url = getApp().globalData.url;
  let header = HEADER;

  if (getApp().globalData.token) {
    header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;
    header['token'] = wx.getStorageSync("cookie_token");
  }
  if (!data) {
    data = {};
  }

  return new Promise((reslove, reject) => {
    wx.request({
      url: Url + '/api/' + api,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
        if (noVerify) {
          reslove(res.data, res);
        } else if (res.data.code == 200) {
          reslove(res.data, res);
        } else if (res.data.code == 401 || res.data.code == 401.2 || res.data.code == 401.3) {
          util.chekWxLogin(1).then(res1 => {
            // 获取路径和参数
            const paramData = wx.getLaunchOptionsSync();
            const path = paramData.path;
            const query = paramData.query;

            // 不能使用redirectTo跳转到tabbar页，需要判断一下
            let queryString = '';
            for (const i in query) {
              queryString += `&${i}=${query[i]}`;
            }

            if (queryString) {
              queryString = `?${queryString.substring(1)}`;
            }

            const fullUrl = `/${path}${queryString}`;
            setTimeout(() => {
              wx.redirectTo({
                url: fullUrl
              });
            }, 100);

            if (res.isLogin) {
              getCurrentPages()[0].onLoad();
              getCurrentPages()[0].onShow();
            }

          })

          // 确实session不提示错误信息
          if (res.data.code !== 401.1) {
            if (res.data.msg != '权限不足' && res.data.msg != '无效的Token') {
              reject(res.data.msg);
            }
          }

        } else if (res.data.code == 411) {
          const paramData = wx.getLaunchOptionsSync();
          const path = paramData.path;

          if (res.data.data.url && path.replace("pages/", " ") == res.data.data.url) {
            getCurrentPages()[0].onLoad();
            getCurrentPages()[0].onShow();
            return
          }

          if (res.data.data.url) {
            if (res.data.data.errmsg) {
              if (res.data.data.url == -1) { //返回
                return getApp().Tips({title: res.data.data.errmsg}, {tab: 3})
              }

              if (!util.isEmpty(res.data.data.type) && res.data.data.type == 1) {
                util.showModelTip(res.data.data.errmsg, "", "前往处理", " ", false).then(result => {
                  wx.redirectTo({
                    url: "/pages/" + res.data.data.url
                  })
                })

                return
              }

              let tab = res.data.data.tab || 5
              getApp().Tips({
                title: res.data.data.errmsg,
                endTime: 1500
              }, {
                tab: tab,
                url: "/pages/" + res.data.data.url
              })

            } else {

              wx.redirectTo({
                url: "/pages/" + res.data.data.url
              })
            }
          } else {
            reject(res.data || '系统错误');
          }
        } else if (res.data.code == 412) {
          return getApp().Tips({title: res.data.data.errmsg})
        } else if (res.data.code == 413) {
          reject(res.data.data || '系统错误');
        } else {
          reject(res.data.msg || '系统错误');
        }
      },
      fail: (msg) => {
        reject('请求失败');
      }
    });
  });
}


['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {});
});
